#include "update.h"
#include "ui_update.h"

Update::Update(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Update)
{
    ui->setupUi(this);
    nextBlockSize=0;
    bytesWritten=0;
    ui->progressBar->setMaximum(0);

    //连接到服务器
    clientSocket=new QTcpSocket(0);
    clientSocket->connectToHost(updateInfo.getIp(),updateInfo.getPort());
    QObject::connect(clientSocket,SIGNAL(readyRead()),this,SLOT(communicate()));
    QObject::connect(clientSocket,SIGNAL(disconnected()),this,SLOT(disconnect()));
}

Update::~Update()
{
    delete ui;
}

void Update::communicate()
{
    QDataStream in(clientSocket);
    in.setVersion(QDataStream::Qt_4_5);
    while(1){
        int bytes=(int)(clientSocket->bytesAvailable());
        //已经接收
        bytesWritten+=bytes;
        if(ui->progressBar->maximum()){
            //设置进度条当前进度
            ui->progressBar->setValue(bytes);
            ui->label_recv->setText(humanDisplay(bytes));
        }
        if (nextBlockSize == 0){
            if (quint64(bytes) < sizeof(quint64)){
                break;
            }
            //总的数据大小
            in >> nextBlockSize;
            //设置进度条最大值
            ui->progressBar->setMaximum((int)nextBlockSize);
            ui->label_tatal->setText(humanDisplay((int)nextBlockSize));
            this->show();
        }
        if (quint64(bytes)<nextBlockSize){
            break;;
        }
        //通信协议
        quint16 protocol;
        in>>protocol;
        switch(protocol){
        case 0x0001:{
            in>>version_s;
            //最新版本，不用升级
            if(updateInfo.getVersion()==version_s){
                QMessageBox::information(this,tr("提示"),tr("当前版本已经是最新的了！"));
                QProcess::startDetached("./run.sh");
                qApp->quit();
            }
            else{
                QByteArray block;
                QDataStream out(&block, QIODevice::WriteOnly);
                out.setVersion(QDataStream::Qt_4_5);
                out<<quint64(0)<<quint16(0x0001);
                out.device()->seek(0);
                out<<quint64(block.size()-sizeof(quint64));
                clientSocket->write(block);
            }
            break;
        }
        case 0x0002:{
            QByteArray block;
            in >> block;
            QFile file("update.xml");
            if(file.open(QIODevice::WriteOnly)&&block.length()!=0){
                file.write(block);
                file.close();
                qDebug() << "Xml file recvice done!";
            }
            if(file.exists()){
                qDebug() << "Read xml file agein!";
                updateInfo.ReadInfoFromXml();

                qDebug() << "Get update file request!";
                QByteArray block;
                QDataStream out(&block, QIODevice::WriteOnly);
                out.setVersion(QDataStream::Qt_4_5);
                out<<quint64(0)<<quint16(0x0002);
                out.device()->seek(0);
                out<<quint64(block.size()-sizeof(quint64));
                clientSocket->write(block);
            }else{
                qDebug() << "The update.xml is not exists!";
            }
            break;
        }
        case 0x0003:{
            int fileCount = updateInfo.fileNameList.length();
            QByteArray block[fileCount];
            for(int i = 0; i < fileCount; i++){
                in >> block[i];
                QFile file(updateInfo.fileNameList[i]);
                if(file.open(QIODevice::WriteOnly)&&block[i].length()!=0){
                    file.write(block[i]);
                    file.close();
                }
            }

            QMessageBox::information(this,tr("升级成功"),"您的软件版本已经从"+updateInfo.getVersion()+"升级到"+version_s+"，将重启启动软件！");
            QString date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss").toUtf8();
            updateInfo.setUpdateDate(date);
            updateInfo.setVersion(version_s.toUtf8());
            updateInfo.SaveInfoToXml();

            //启动主程序
            system("./run.sh");
            qApp->quit();
            break;
        }
        }
        nextBlockSize=0;
    }
}

QString Update::humanDisplay(int bytes)
{
    double kb = bytes / 1024;
    if(kb < 1024){
        return QString::number(kb,'f',2) + QString("KB");
    }else{
        double mb = kb / 1024;
        if(mb < 1024){
            return QString::number(mb,'f',2) + QString("MB");
        }else{
            double gb = mb / 1024;
            return QString::number(gb,'f',2) + QString("GB");
        }
    }
}

void Update::disconnect()
{
    clientSocket->deleteLater();
    QMessageBox::information(this,tr("错误"),tr("网络连接中断！"));
    qApp->quit();
}
